// pages/doctor/patient/patient.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    patient_id: 0,
    isEditing: false,
    //基础信息
    basalInfo: {
      name: null, //姓名
      phone: "暂无", //电话
      ifGenderIndex: null, //性别
      age: null, //年龄
      bw: 62.0, //体重
      bh: 1.75, //身高
      diaTypeIndex: 0, //糖尿病类型
      smoke: 0, //吸烟年限
      ifDrinkIndex: null, //是否饮酒
      di: null, //糖尿病年限
      ifMacroIndex: null, //是否患大血管并发症
      ifMicroIndex: null, //是否患微血管并发症
      hba1c: null, //糖化血红蛋白
      ifHypoglycemiaIndex: null, //是否低血糖
      ageIndex: 0, //年龄段
      ifCureIndex: 0, //是否接受过治疗
      cureTDI: 23, //已接受治疗的患者的每日胰岛素总量（U）
      bgConIndex: 0, //血糖控制情况
    //   idealBG: [4.2, 6.6, 6.4, 7.6],
      idealBG:[4.4, 6.9, 6.7, 8.0]
    },

    ageGroup: ['青春期前期', '青春期至成年人', '成年人'],
    diaTypeArray: ['1型糖尿病', '2型糖尿病', '妊娠性糖尿病', '其他'],
    ifCureArray: ['否', '是'],
    BGConArray: ['控制良好', '经常低血糖', '经常高血糖'],
    drugRecommend: [],

    //胰岛素泵6个时间段设置
    pumpTimeSlice: ['00:00-03:00', '03:00-08:00', '08:00-12:00', '12:00-16:00', '16:00-20:00', '20:00-24:00'],
    showOld: false,
    //历史胰岛素方案
    oldInsulinPlan: {
      oldTDI: 45, //全天胰岛素总剂量
      oldBasalTDI: 24, //全天基础胰岛素总量
      oldBolusTDI: 21, //全天餐时胰岛素总量
      oldBasalInject: 1.0, //基础注射率（24小时平均）
      oldPumpSlice: [0.6, 1.2, 0.8, 0.9, 1.1, 0.8], //六个基础时间段胰岛素注射率
      oldBolusSlice: [8.4, 7, 7], //三个餐时胰岛素剂量
    },
    //历史针剂方案
    oldInjectPlan: {
      morningBolus: 8.4, //早餐前（速效）
      afternoonBolus: 7, //午餐前（速效）
      eveningBolus: 7, //晚餐前（速效）
      bedtimeBasal: 22.2, //睡前（长效）
    },
  },

  // 跳转到PatientDataUpload界面
  goPatientDataUpload() {
    wx.navigateTo({
      url: `/pages/dataupload/dataupload?patient_id=${this.data.patient_id}`,
    });
  },

  // 跳转到InsulinDoseOriginal页面
  goInsulinDoseOriginal() {
    var basalInfo = this.data.basalInfo
    console.log('basalInfo', basalInfo)
    // if(this.data.diaTypeArray[basalInfo.diaTypeIndex] == '2型糖尿病'){
    //   const BMI = basalInfo.bw / (basalInfo.bh * basalInfo.bh / 100 / 100)
    //   console.log('BMI',BMI)
    //   if (BMI<=23.9){
    //     basalInfo.bw *= 0.5
    //   }else if(BMI>=24.0 && BMI<=27.9){
    //     basalInfo.bw *= 0.7
    //   }
    // }
    const basalInfoStr = encodeURIComponent(JSON.stringify(this.data.basalInfo));

    // console.log("hello", this.data.patient_id)
    wx.navigateTo({
      url: `/pages/insulinDoseOriginal/insulinDoseOriginal?patient_id=${this.data.patient_id}&basalInfo=${basalInfoStr}`,
    });
  },

  // 跳转到InsulinDoseAdjust页面
  goInsulinDoseAdjust() {
    const basalInfoStr = encodeURIComponent(JSON.stringify(this.data.basalInfo));
    wx.navigateTo({
      url: `/pages/insulinDoseAdjust/insulinDoseAdjust?patient_id=${this.data.patient_id}&basalInfo=${basalInfoStr}`,
    });
  },

  toggleEdit() {
    const {
      isEditing
    } = this.data;
    if (isEditing) {
      this.saveData();
    }

    this.setData({
      isEditing: !isEditing,
    });
  },

  saveData() {
    const {
      basalInfo
    } = this.data;

    console.log(basalInfo)
    wx.request({
      url: `${app.globalData.protocol}://${app.globalData.host}/bgmp/api/doctor?Action=UpdatePatient`,
      method: 'POST',
      header: {
        "Content-Type": "application/json",
        "x-api-key": wx.getStorageSync('token'),
      },
      data: {
        "id": parseInt(this.data.patient_id),
        "name": basalInfo.name,
        "phone": basalInfo.phone,
        "gender": basalInfo.ifGenderIndex,
        "age": parseFloat(basalInfo.age),
        "weight": parseFloat(basalInfo.bw),
        "height": parseFloat(basalInfo.bh),
        "smoke": parseFloat(basalInfo.smoke),
        "alcohol": basalInfo.ifDrinkIndex,
        "diabetes": parseFloat(basalInfo.di),
        "macro": basalInfo.ifMacroIndex,
        "micro": basalInfo.ifMicroIndex,
        "hba1c": parseFloat(basalInfo.hba1c),
        "hypoglycemia": basalInfo.ifHypoglycemiaIndex,
        "typeofdiabetes": this.data.diaTypeArray[basalInfo.diaTypeIndex]
      },
      success: (res) => {
        console.log(res);
        if (res.data.code === 200) {
          wx.showToast({
            title: '更新患者成功',
            icon: 'success',
            duration: 2500,
          });
        } else {
          wx.showToast({
            title: '更新患者失败',
            icon: 'none',
            duration: 2500,
          });
        }
      },
      fail: (res) => {
        wx.showToast({
          title: '更新患者失败',
          icon: 'none',
          duration: 2500,
        });
      }
    });
  },

  onInputName(e) {
    // console.log('name值变更为', e.detail.value)
    var value = e.detail.value;
    var basalInfo = this.data.basalInfo
    basalInfo.name = value;
    this.setData({
      basalInfo: basalInfo // 将用户输入的内容保存到 data 中
    });
  },
  onInputPhone(e) {
    // console.log('phone值变更为', e.detail.value)
    var value = e.detail.value;
    var basalInfo = this.data.basalInfo
    basalInfo.phone = value;
    this.setData({
      basalInfo: basalInfo // 将用户输入的内容保存到 data 中
    });
  },

  selectMale(e) {
    var basalInfo = this.data.basalInfo
    basalInfo.ifGenderIndex = 1
    this.setData({
      basalInfo: basalInfo,
    });
  },

  selectFemale(e) {
    var basalInfo = this.data.basalInfo
    basalInfo.ifGenderIndex = 2
    this.setData({
      basalInfo: basalInfo,
    });
  },

  onInputAge(e) {
    // console.log('age值变更为', e.detail.value)
    var value = e.detail.value;
    var basalInfo = this.data.basalInfo
    basalInfo.age = value;
    this.setData({
      basalInfo: basalInfo // 将用户输入的内容保存到 data 中
    });
  },

  // 更新体重
  updateBW(e) {
    const {
      value
    } = e.detail;
    var baseInfo = this.data.basalInfo
    baseInfo.bw = value;
    this.setData({
      basalInfo: baseInfo // 将用户输入的内容保存到 data 中
    });
  },

  onInputBh: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      ['basalInfo.bh']: e.detail.value
    })
    console.log(this.data.basalInfo)
  },

  // 更新身高
  updateBh(e) {
    const {
      value
    } = e.detail;
    var baseInfo = this.data.basalInfo
    baseInfo.bh = value;
    this.setData({
      basalInfo: baseInfo // 将用户输入的内容保存到 data 中
    });
  },

  selectYes() {
    var baseInfo = this.data.basalInfo
    baseInfo.ifCureIndex = 1
    this.setData({
      basalInfo: baseInfo,
      ifShow: baseInfo.ifCureIndex > 0 ? true : false,
    });
    console.log("baseInfo", baseInfo)
    console.log("ifShow", this.data.ifShow)
  },

  selectNo() {
    var baseInfo = this.data.basalInfo
    baseInfo.ifCureIndex = 0
    this.setData({
      basalInfo: baseInfo,
      ifShow: baseInfo.ifCureIndex > 0 ? true : false,
    });
    console.log("baseInfo", baseInfo)
    console.log("ifShow", this.data.ifShow)
  },

  //数字输入框（体重）
  onInputBw: function (e) {
    console.log('input发送选择改变，携带值为', e.detail.value)
    this.setData({
      ['basalInfo.bw']: e.detail.value
    })
  },

  //数字输入框（身高）
  onInputHw: function (e) {
    console.log('input发送选择改变，携带值为', e.detail.value)
    this.setData({
      ['basalInfo.hw']: e.detail.value
    })
  },

  //普通选择器（年龄段）
  ageGroupBindPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      ['basalInfo.ageIndex']: e.detail.value
    })
  },

  //普通选择器（糖尿病类型）
  diaTypeBindPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      ['basalInfo.diaTypeIndex']: e.detail.value
    })
  },

  //数字输入框（目标血糖）
  idealBGBindInput0: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      ['basalInfo.idealBG[0]']: e.detail.value.toFixed(1)
    })
  },
  idealBGBindInput1: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      ['basalInfo.idealBG[1]']: e.detail.value.toFixed(1)
    })
  },
  idealBGBindInput2: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      ['basalInfo.idealBG[2]']: e.detail.value.toFixed(1)
    })
  },
  idealBGBindInput3: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      ['basalInfo.idealBG[3]']: e.detail.value.toFixed(1)
    })
  },

  onInputSmoke(e) {
    console.log('smoke值变更为', e.detail.value)
    var value = e.detail.value;
    var basalInfo = this.data.basalInfo
    basalInfo.smoke = value;
    this.setData({
      basalInfo: basalInfo // 将用户输入的内容保存到 data 中
    });
  },

  selectDrinkYes(e) {
    var basalInfo = this.data.basalInfo
    basalInfo.ifDrinkIndex = 1
    this.setData({
      basalInfo: basalInfo,
    });
  },

  selectDrinkNo(e) {
    var basalInfo = this.data.basalInfo
    basalInfo.ifDrinkIndex = 0
    this.setData({
      basalInfo: basalInfo,
    });
  },

  onInputDI(e) {
    // console.log('illness duration值变更为', e.detail.value)
    var value = e.detail.value;
    var basalInfo = this.data.basalInfo
    basalInfo.di = value;
    this.setData({
      basalInfo: basalInfo // 将用户输入的内容保存到 data 中
    });
  },

  selectMacroYes(e) {
    var basalInfo = this.data.basalInfo
    basalInfo.ifMacroIndex = 1
    this.setData({
      basalInfo: basalInfo,
    });
  },

  selectMacroNo(e) {
    var basalInfo = this.data.basalInfo
    basalInfo.ifMacroIndex = 0
    this.setData({
      basalInfo: basalInfo,
    });
  },

  selectMicroYes(e) {
    var basalInfo = this.data.basalInfo
    basalInfo.ifMicroIndex = 1
    this.setData({
      basalInfo: basalInfo,
    });
  },

  selectMicroNo(e) {
    var basalInfo = this.data.basalInfo
    basalInfo.ifMicroIndex = 0
    this.setData({
      basalInfo: basalInfo,
    });
  },

  onInputHba1c(e) {
    // console.log('hba1c值变更为', e.detail.value)
    var value = e.detail.value;
    var basalInfo = this.data.basalInfo
    basalInfo.hba1c = value;
    this.setData({
      basalInfo: basalInfo // 将用户输入的内容保存到 data 中
    });
  },

  selectHypoglycemiaYes(e) {
    var basalInfo = this.data.basalInfo
    basalInfo.ifHypoglycemiaIndex = 1
    this.setData({
      basalInfo: basalInfo,
    });
  },

  selectHypoglycemiaNo(e) {
    var basalInfo = this.data.basalInfo
    basalInfo.ifHypoglycemiaIndex = 2
    this.setData({
      basalInfo: basalInfo,
    });
  },

  //普通选择器（是否接受过治疗）
  ifCureBindPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
        ['basalInfo.ifCureIndex']: e.detail.value
      }),
      this.setData({
        ifShow: this.data.basalInfo.ifCureIndex > 0 ? true : false,
      })
  },

  //数字输入（已接收治疗的每日胰岛素剂量）
  cureTDIBindInput: function (e) {
    console.log('input发送选择改变，携带值为', e.detail.value)
    this.setData({
      ['basalInfo.cureTDI']: e.detail.value
    })
  },

  //普通选择器（血糖控制情况）
  bgConBindPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      ['basalInfo.bgConIndex']: parseInt(e.detail.value)
    })
    console.log('basalInfo', this.data.basalInfo)
  },

  //早餐时间
  breakfastbindDateChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      ['dailyLife.breakfast']: e.detail.value
    })
  },

  //午餐时间
  lunchbindDateChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      ['dailyLife.lunch']: e.detail.value
    })
  },

  //早餐时间
  dinnerbindDateChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      ['dailyLife.dinner']: e.detail.value
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log("你好，患者基础信息")
    this.setData({
      patient_id: parseInt(options.id)
    })
    console.log(this.data.patient_id)
    //从后端获取病人基础信息
    wx.request({
      url: `${app.globalData.protocol}://${app.globalData.host}/bgmp/api/doctor?Action=GetPatientDetail`,
      method: 'POST',
      header: {
        "Content-Type": "application/json",
        "x-api-key": wx.getStorageSync('token'),
      },
      data: {
        //这里要用parseInt，不然后端会将id值识别为string，即使前端确实传的是数值
        "patient_id": parseInt(this.data.patient_id)
      },
      success: (res) => {
        // console.log("返回患者信息：", res)
        var patient = res.data.message
        console.log("返回患者信息：", patient)

        this.setData({
          ['basalInfo.name']: patient.username,
          ['basalInfo.ifGenderIndex']: patient.gender,
          ['basalInfo.age']: patient.age,
          ['basalInfo.bw']: patient.weight,
          ['basalInfo.bh']: patient.height,
          ['basalInfo.smoke']: patient.smoking_history,
          ['basalInfo.di']: patient.duration_of_diabetes,
          ['basalInfo.hba1c']: patient.hba1c,
          ['basalInfo.ifHypoglycemiaIndex']: patient.hypoglycemia,
        })

        var phone = patient.phone;
        if (phone != "") {
          this.setData({
            ['basalInfo.phone']: phone
          })
        }

        var age = patient.age;
        if (age >= 10 && age <= 14) {
          this.setData({
            ['basalInfo.ageIndex']: 0
          })
        } else if (age > 14 && age <= 18) {
          this.setData({
            ['basalInfo.ageIndex']: 1
          })
        } else if (age > 18) {
          this.setData({
            ['basalInfo.ageIndex']: 2
          })
        }

        var diaType = patient.type_of_diabetes
        if (diaType == "T1DM" || diaType == "1型糖尿病") {
          this.setData({
            ['basalInfo.diaTypeIndex']: 0
          })
        } else if (diaType == "T2DM" || diaType == "2型糖尿病") {
          this.setData({
            ['basalInfo.diaTypeIndex']: 1
          })
        } else if (diaType == "GDM" || diaType == "妊娠性糖尿病") {
          this.setData({
            ['basalInfo.diaTypeIndex']: 2
          })
        } else if (diaType == "其他") {
          this.setData({
            ['basalInfo.diaTypeIndex']: 3
          })
        }

        var ifDrink = patient.alcohol_drinking_history
        if (ifDrink == "non-drinker") {
          this.setData({
            ['basalInfo.ifDrinkIndex']: 0
          })
        } else {
          this.setData({
            ['basalInfo.ifDrinkIndex']: 1
          })
        }
  
        var ifMacro = patient.diabetic_macrovascular_complications
        if (ifMacro == "none") {
          this.setData({
            ['basalInfo.ifMacroIndex']: 0
          })
        } else {
          this.setData({
            ['basalInfo.ifMacroIndex']: 1
          })
        }

        var ifMicro = patient.diabetic_microvascular_complications
        if (ifMicro == "none") {
          this.setData({
            ['basalInfo.ifMicroIndex']: 0
          })
        } else {
          this.setData({
            ['basalInfo.ifMicroIndex']: 1
          })
        }
      }
    })

    //获取药物推荐
    wx.request({
      url: `${app.globalData.protocol}://${app.globalData.host}/bgmp/api/algorithm?Action=Agent`,
      method: 'POST',
      header: {
        "Content-Type": "application/json",
        "x-api-key": wx.getStorageSync('token'),
      },
      data: {
        "time": Math.round(new Date().getTime() / 1000),
        //这里要用parseInt，不然后端会将id值识别为string，即使前端确实传的是数值
        "patient_id": parseInt(this.data.patient_id)
      },
      success: (res) => {
        console.log(res)
        if (res.data.code == 200)  {
          console.log("返回用药推荐信息：", res.data.message)
          this.setData({
            drugRecommend: this.groupDrugs(res.data.message)
          });
        }
      }
    })

    this.getOldInsulinPlan()
  },
  getOldInsulinPlan() {
    wx.request({
      url: `${app.globalData.protocol}://${app.globalData.host}/bgmp/api/insulin?Action=GetInsulinTherapy`,
      method: 'POST',
      header: {
        "Content-Type": "application/json",
        "x-api-key": wx.getStorageSync('token'),
      },
      data: {
        'patient_id': this.data.patient_id,
        'before': Math.floor(Date.now() / 1000),
      },
      success: (res) => {
        console.log("历史方案：", res)
        var therapy = res.data.message.therapy
        if (res.data.code == 200) {
          var oldInsulinPlan = {
            oldTDI: therapy.tdi, //全天胰岛素总剂量
            oldBasalTDI: therapy.basal_tdi, //全天基础胰岛素总量
            oldBolusTDI: therapy.bolus_tdi, //全天餐时胰岛素总量
            oldBasalInject: therapy.basal_inject, //基础注射率（24小时平均）
            oldPumpSlice: [
              therapy.pump_0_3,
              therapy.pump_3_8,
              therapy.pump_8_12,
              therapy.pump_12_16,
              therapy.pump_16_20,
              therapy.pump_20_24,
            ], //六个基础时间段胰岛素注射率
            oldBolusSlice: [
              therapy.breakfast_bolus,
              therapy.lunch_bolus,
              therapy.dinner_bolus,
            ], //三个餐时胰岛素剂量
          }
          //历史针剂方案
          var oldInjectPlan = {
            morningBolus: therapy.breakfast_bolus, //早餐前（速效）
            afternoonBolus: therapy.lunch_bolus, //午餐前（速效）
            eveningBolus: therapy.dinner_bolus, //晚餐前（速效）
            bedtimeBasal: therapy.bedtime_basal, //睡前（长效）
          }
          this.setData({
            oldInsulinPlan: oldInsulinPlan,
            oldInjectPlan: oldInjectPlan,
            showOld: therapy.ID != 0 ? true : false
          })
        } else {
          wx.showToast({
            title: '历史方案获取失败',
            icon: 'none',
            duration: 2000 //持续的时间
          })
        }
      }
    })
  },

  groupDrugs(message) {
    var drugRecommend = []
    for (let i = 0; i < message.length; i++) {
      var drugs = message[i]
      var group = []
      for (let j = 0; j < drugs.length; j += 2) {
        group.push(drugs.slice(j, j + 2));
      }
      drugRecommend.push(group)
    }
    return drugRecommend
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getOldInsulinPlan()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})